package com.rtsapp.server.gamelog.client.socket;

import com.rtsapp.server.common.ByteBuffer;
import com.rtsapp.server.gamelog.cmd.cmd.Commands;
import com.rtsapp.server.logger.Logger;
import com.rtsapp.server.logger.LoggerFactory;
import com.rtsapp.server.network.protocol.command.ICommand;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 日志Handler
 */
public class LogInHandler extends ChannelInboundHandlerAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogInHandler.class);

    private static final int LEN_FIELD_LEN = 4;
    private static final int COMMAND_ID_LEN = 4;

    private final ISocketHandler socketHandler;

    public LogInHandler(ISocketHandler socketHandler) {
        this.socketHandler = socketHandler;
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {


        if (msg instanceof ByteBuf) {


            ByteBuf data = (ByteBuf) msg;

            try {

                ByteBuffer buffer = new ByteBuffer(data);

                //收到消息
                if (buffer.readableBytes() < (LEN_FIELD_LEN + COMMAND_ID_LEN)) {
                    LOGGER.error("包长度错误 长度字段 < " + (LEN_FIELD_LEN + COMMAND_ID_LEN));
                    LOGGER.error("数据包头部错误, 将关闭连接");
                    ctx.close();
                    return;
                }


                //读取包的长度, 这句代码不嗯给你删除
                int packLength = buffer.readInt();
                int commandId = buffer.getInt(buffer.readerIndex());


                //创建Request, Response
                ICommand response = Commands.createResponse(commandId);
                if (response == null) {
                    LOGGER.error("  CommandFactory.createRequest ==null ");
                    return;
                }


                //读取request, 如果有异常报错
                try {
                    response.readFromBuffer(buffer);
                } catch (Throwable ex) {
                    LOGGER.error(" request.readFromBuffer( buffer ) 错误 ", ex);
                    ctx.close();
                    return;
                }

                socketHandler.onRecieve(ctx, commandId, response);

            } catch (Throwable ex) {
                LOGGER.error("数据包处理错误", ex);
            } finally {
                //释放引用计数
                data.release();
            }

        } else {
            LOGGER.info("channelRead msg 不是ByteBuf..");
        }

    }


    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 连接建立
        socketHandler.onConnect(ctx);
    }

    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //连接关闭
        socketHandler.onClose(ctx);
    }


}
